<?php
/**
 * @file $HeadURL: user.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2015-4-1 下午4:04:25 $
 * @brief 
 */
namespace haibao\user\data;

use haibao\www\Config;
use haibao\frame\http\Cookie;
use haibao\user\data\User as UserData;

class authuser extends \haibao\user\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\user\model\data\authuser');
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
	}
	
	public function signIn($userId,$credit){
		$this->beginTranscation();
		try{
			$sql = 'insert into hb_bussiness_sign_info(uid,sign_time,this_credit) values('.$userId.','.time().','.$credit.')';
			$this->query($sql);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		 
		$this->endTranscation();
	}
	
	public function getContinuousSignDays($userId,$time){
		$endTime = strtotime(date('Y-m-d',strtotime($time)));
		$startTime = $endTime - 86400*7;
		$sql = 'select count(*) as num from hb_bussiness_sign_info where uid=%s and sign_time >= %s and sign_time < %s';
		$result = $this->query($sql,array(
				$userId,
				$startTime,
				$endTime
		));
		$result->fetch_assoc();
		$num = $result->getData('num');
		 
		return $num;
	}
	
	public function checkSignIn($userId,$time){
		$isSign = false;
		$startTime = strtotime(date('Y-m-d',strtotime($time)));
		$endTime = $startTime + 86400 - 1;
		$sql = 'select count(*) as num from hb_bussiness_sign_info where uid=%s and sign_time >= %s and sign_time <= %s';
		$result = $this->query($sql,array(
				$userId,
				$startTime,
				$endTime,
		));
		 
		$result->fetch_assoc();
		if ($result->getData('num')){
			$isSign = true;
		}
		 
		return $isSign;
	}
	
	public function getUserByUserId($userId){
		return $this->getOneById($userId);
	}
	
	public function getUsersByIds($Ids){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $Ids));
		$sql = "select * from `auth_user` where id in (".$str.")";
		$result = $this->query($sql, $Ids);
		$returnUserName = array();
		while ($row = $result->fetch_assoc()){
//         $returnUserName[$row->id] = $row;
           $returnUserName[$row['id']] = $row;
           
		}
		return $returnUserName;
	}
	
	public function getUsernamesByUserIds($Ids){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $Ids));
		$sql = "select id,username from `auth_user` where id in (".$str.")";
		$result = $this->query($sql, $Ids);
		$returnUserName = array();
		while ($result->fetch_assoc()){
			$returnUserName[$result->getData('id')] = $result->getData('username');
		}
		return $returnUserName;
	}
	
	public function getNickNameByUserIds($Ids){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $Ids));
		$sql = "select id,nickname from `auth_user` where id in (".$str.")";
		$result = $this->query($sql, $Ids);
		$nickNames = array();
		while ($result->fetch_assoc()){
			$nickNames[$result->getData('id')] = $result->getData('nickname');
		}
		return $nickNames;
	}
	
	public function getUserPariseAndReplyById($id){
	    $sql = 'select * from `auth_user` where id=%s';
	    $result = $this->query($sql, array($id));
	    return $result->fetch_assoc();
	}
	
	
	public function getUserByMobile($mobile){
		$sql = 'select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where mobile=%s limit 1';
		$result = $this->query($sql, array(
			$mobile
		));
		return $result->fetch_assoc();
	}
	
	public function getUserByEmail($email){
		$sql = "select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where email=%s limit 1";
		$result = $this->query($sql, array(
				$email
		));
		return $result->fetch_assoc();
	}
	
	public function getUserByNickname($nickname){
		$sql = "select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where nickname=%s limit 1";
		$result = $this->query($sql, array(
				$nickname
		));
		return $result->fetch_assoc();
	}
	
	public function getUserByUsername($username){
		$sql = "select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where username=%s limit 1";
		$result = $this->query($sql, array(
				$username
		));
		return $result->fetch_assoc();
	}
	
	public function getUserListByUserName($username){
	    $sql = "select id,nickname,username,password,email,mobile,is_active from `auth_user` where username like %s";          
	    $result = $this->query($sql, array(
	        '%'.$username.'%'
	    ));
	    
	    $userNameList = array();
	    while ($list = $result->fetch_assoc()){
	        $userNameList[$list['id']] = $list;
	    }
	    return $userNameList;
	}
	
	public function getUserByHBUser($username){
		$sql = "select id,nickname,username,password,email,mobile,is_active from `auth_user` where username=%s or mobile=%s limit 1";
		$result = $this->query($sql, array(
				$username, $username
		));
		return $result->fetch_assoc();
	}
	
	/**
	 * 保存用户信息
	 * @param \haibao\user\model\data\authuser $model
	 */
	public function saveUser($model, $type = null, $thirdId = null, $avator = null){
		$this->beginTranscation();
		try {
			$this->add($model);
			
			if(!$model->nickname){
    			$hbName = '报友'.$model->Id;
    			if(!empty($model->mobile)){
    			    $upData['nickname'] = $upData['username'] = $hbName;
    			    $model->username = $hbName;
    			}else{
    			    $upData['nickname'] = $model->username;
    			}
    			$this->updateById($model->Id, $upData);
			}
			
			// 保存第三方登录帐号
			if($model->Id > 0 && $type && $thirdId){
				$this->addBind($type, $model->Id, $thirdId);
			}
			
			if($model->Id > 0){
				$profileModel = new \haibao\user\model\data\SnsMyProfile();
				$profileModel->user_id = $model->Id;
				$profileModel->avatar = $avator;
				$profileModel->username = $model->username;
				$profileModel->last_online = new \DateTime();
				$profileModel->last_ip = $model->last_ip;
				$profileModel->is_email_verified = \haibao\user\model\data\SnsMyProfile::EMAIL_VERIFIED_NO;
				$profileModel->is_mobile_verified = !empty($model->mobile) ? \haibao\user\model\data\SnsMyProfile::MOBILE_VERIFIED_YES : \haibao\user\model\data\SnsMyProfile::MOBILE_VERIFIED_NO;
				
				$data = new \haibao\user\data\SnsMyProfile();
				$data->addSnsProfile($profileModel);
			}
			
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function setUserAuater($userId,$avatar){
		$this->beginTranscation();
		try {
			$this->query("update sns_myprofile set avatar=%s where user_id=%s limit 1", array($avatar, $userId));
			$avatar_md5 = md5($avatar);
			$this->query("update auth_user set avatar_md5=%s where id=%s limit 1", array($avatar_md5, $userId));
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 设置用户头像、性别、昵称
	 * @param int $userId	用户ID
	 * @param \haibao\user\model\data\UserReg $userModel
	 * @throws BusinessException
	 */
	public function setUserInfo($userId, $userModel){
		$this->beginTranscation();
		try {
			$this->query("update sns_myprofile set avatar=%s,gender=%s where user_id=%s", array(
					$userModel->AvatarUrl, $userModel->Gender, $userId
			));
	
			$this->query("update auth_user set nickname=%s,avatar_md5=%s where id=%s", array(
					$userModel->NickName, $userModel->AvatarMd5, $userId
			));
	
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 更改邮箱激活状态为已激活
	 */
	public function updateEmailVerify($userId, $token){
		$sql = 'update snsmyprofile set is_email_verified=%s where user_id=%s limit 1';
		$this->query($sql, array(
			\haibao\user\model\data\SnsMyProfile::EMAIL_VERIFIED_YES, (int)$userId
		));
		$cache = new \haibao\user\cache\User();
		$cache->deleteToken($token);
	}
	
	/**
	 * 重置数据库中的密码
	 */
	public function resetPassword($userId, $password, $token = null){
		$sql = 'update auth_user set password=%s where id=%s limit 1';
		$this->query($sql, array(
			$password, $userId
		));
	}
	
	/**
	 * 添加发短信黑名单列表
	 */
	public function updateBlackList($userList){
	    $data = new \haibao\user\cache\User();
	    $data->updateBlackList($userList);
	}
	
	/**
	 * 查找用户是否在黑名单中
	 */
	public function inBlackList($userId){
	    $data = new \haibao\user\cache\User();
	    return $data->inBlackList($userId);
	}
	
	public function getBlackSig(){
	    $data = new \haibao\user\cache\User();
	    return $data->getBlackSig();
	}
	
	public function getBlackList(){
	    $this->setConfig( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS) );
	    $limitTime = date('Y-m-d H:i:s', strtotime('-15 days'));
	    $sql = 'select count(*) as count, Mobile from `SmsLog` where CreateTime>=%s group by Mobile having count >%s  order by count desc';
	    $result = $this->query($sql, array($limitTime, 15));
	    
	    $blackList = array();
	    while ($result->fetch_assoc()){
	        array_push($blackList, $result->getData('Mobile'));
	    }
	    $this->setConfig( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3) );
	    return $blackList;
	}
	
	/**
	 * 更新用户最后登录时间
	 */
	public function updateLastLoginTime($userId, $ip){
		$this->updateById($userId, array(
				\haibao\user\model\filter\authuser::CONDITION_FIELD_LAST_LOGIN => new \DateTime()
		));
			
		$sql = 'update sns_myprofile set last_online=%s,last_ip=%s where user_id=%s limit 1';
		$this->query($sql, array(
				date('Y-m-d H:i:s'), $userId, $ip
		));
	}
	
	public function updateCommentNum($userId){
		$sql = 'update auth_user set reply_num=reply_num+1 where id=%s';
		$this->query($sql,array($userId));
	}
	
	public function updatePraiseNum($userId){
		$sql = 'update auth_user set praise_num=praise_num+1 where id=%s';
		$this->query($sql,array($userId));
	}
	
	/**
	 * 记录登录日志
	 */
	public function addLoginLog($userId, $username, $ip){
		$sql = "insert into hb_zj_login_log_byx(`uid`,`username`,`logintime`,`ip`) values(%s,%s,%s,%s)";
		$this->query($sql, array(
			$userId, $username, date('Y-m-d H:i:s'), $ip
		));
	}
	
	/**
	 * 退出登录，删除session和cookie
	 */
	public function delSession(){
		$sessionId = Cookie::get(Config::$cookie['cookie_key']);
		$cache = new \haibao\user\cache\User();
		$cache->delSession($sessionId);
		
		Cookie::remove(Config::$cookie['cookie_key'], Config::$cookie['cookie_path'], Config::$cookie['cookie_domain']);
		Cookie::remove(Config::$cookie['old_cookie_key'], Config::$cookie['cookie_path'], Config::$cookie['cookie_domain']);
		$this->delVisitorCookie();
		if( extension_loaded('tokyo_tyrant') ){
			$tt = new \TokyoTyrantTable(Config::$ttserver['ttserver_host'], Config::$ttserver['ttserver_port']);
			$tt->out($sessionId);
		}
	}
	
	/**
	 * 写session到redis中（7天内有效，与存储在客户端的cookie保持一致）
	 * @param \haibao\user\model\data\authuser $model
	 */
	public function writeSession($userId, $remberMe = true, $model = null){
		
		$this->delSession();
		
		$expire = time() + Config::$cookie['cookie_expire']; //过期的时间
		$key = $this->getSessionId($userId);
		
		$userInfo = $this->getUserByUserId($userId);
		
		$avator = 'http://bbs.haibao.com/uc_server/avatar.php?uid='.$userId.'&size=middle';
		
		// 消息数量
		//$msgCount = (int)$this->getMessageCount($userId);
		$msgCount = 0;
		
		if(!$userInfo && $model){
		    $userInfo = $model;
		}
		$strn = 'j2(4b05c_4((o+0penbd5x6w^2*lx3ol)pk!my#vzr+&964ln1';
		$value = '_auth_user_id = L' . $userId . 'L.';
		$value .= '_auth_nick_name = L' . $userInfo->nickname . 'L.';
		$value .= '_auth_user_name = L' . $userInfo->username . 'L.';
		$value .= '_auth_user_mobile = L' . (!empty($userInfo->mobile) ? $userInfo->mobile : '') . 'L.';
		$value .= '_auth_user_email = L' . (!empty($userInfo->email) ? $userInfo->email : '' ) . 'L.';
		$value .= '_auth_user_avator = L' . $avator ."L.";
		$value .= '_auth_user_msg_count = L' . $msgCount ."L.";
		
		$value = base64_encode($value . md5($value.$strn));
		
		$cache = new \haibao\user\cache\User();
		$cache->setSession($key, $value, $expire);
		
		if($remberMe){
			Cookie::set(Config::$cookie['cookie_key'], $key, $expire, Config::$cookie['cookie_path'], Config::$cookie['cookie_domain']);
			setcookie(Config::$cookie['old_cookie_key'], $key, $expire, Config::$cookie['cookie_path'], Config::$cookie['cookie_domain']);
		}
		
		// 旧版前台系统部分频道不试用新系统，需要做登录兼容（********正式上线后打开********）
		if( extension_loaded('tokyo_tyrant') ){
			$tt = new \TokyoTyrantTable(Config::$ttserver['ttserver_host'], Config::$ttserver['ttserver_port']);
			$strn = "j2(4b05c_4((o+0penbd5x6w^2*lx3ol)pk!my#vzr+&964ln1";
			$value = "(dp1\nS'_auth_user_backend'\np2\nS'django.contrib.auth.backends.ModelBackend'\np3\nsS'_auth_user_id'\np4\nL{$userId}L\ns.";
			$value_md5 = md5($value.$strn);
			$value = base64_encode($value.$value_md5);
			$values = array(
					'data' => $value,
					'expire' => $expire
				);
			$result = $tt->put($key, $values);
		}
	}
	
	public function writeVisitorCookie($isFromComment = true){
		$rand = mt_rand(1000, 9999);
		$unRegId = 10000000+$rand+mt_rand(1, 999);
		$name = '海报用户'.$rand;
		$value = $unRegId.'###'.$name."###1";
		$expire = time()+3600*24*30;
		Cookie::$cookie = null;
		if($isFromComment){
			Cookie::set(\haibao\comment\Config::$cookie['cookie_key'].'_visitor_id', $value, $expire,\haibao\comment\Config::$cookie['cookie_path'], \haibao\comment\Config::$cookie['cookie_domain']);
		}else{
			Cookie::set(Config::$cookie['cookie_key'].'_visitor_id', $value, $expire,Config::$cookie['cookie_path'], Config::$cookie['cookie_domain']);
		}
		return true;
		
	}
	
	public function delVisitorCookie(){
		$key = Config::$cookie['cookie_key'].'_visitor_id';
		Cookie::set($key, null, time()-1, Config::$cookie['cookie_path'], Config::$cookie['cookie_domain']);
	}
	/**
	 * 走数据库方式发送邮件
	 */
	public function sendMail($subject, $content, $mailto, $from = null){
	    if(!$from){
	        $from = \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MAIL_SENDER_ADDRESS);
	    }
		$sql = 'insert into z_email_queue(`fromname`, `mailto`, `subject`, `content`, `contenttype`, `addtime`) values(%s,%s,%s,%s,%s,%s)';
		$this->query($sql, array(
			$from, $mailto, $subject, $content, 1, date('Y-m-d H:i:s'),
		));
	}
	
	/**
	 * 根据token获取用户ID
	 */
	public function getUserIdByToken($token){
		$cache = new \haibao\user\cache\User();
		return $cache->getUserByToken($token);
	}
	
	/**
	 * 根据用户ID获取邮箱手机找回密码的激活码（默认保留3天）
	 */
	public function getToken($userId){
		$token = time().'_'.$userId.'_'.rand(1000, 10000);
		$token = sha1($token);
	
		$cache = new \haibao\user\cache\User();
		$cache->setToken($token, $userId);
		return $token;
	}
	
	/**
	 * 获取手机验证码
	 */
	public function getSmsCaptcha($mobile){
		$cache = new \haibao\user\cache\User();
		$code = $this->generateCode();
		$cache->setSmsCaptcha($mobile, $code, 60*10);
		
		return $code;
	}
	
	/**
	 * 获取某手机发送验证码次数
	 */
	public function getSendCount($mobile){
		$cache = new \haibao\user\cache\User();
		return $cache->getSmsSendCount($mobile);
	}
	
	/**
	 * 添加标签
	 * @param array $data
	 */
	public function addSign($data){
		
		$userData = new UserData;
		$credit = $userData->addUserIntegral($data['userId'],date('Y-m-d H:i:s'),UserData::USER_INTEGRAL_SIGN);
		$time = time();
		if($credit){
			$sql="insert into hb_bussiness_sign_info (uid,sign_time,this_credit) value (%s,%s,%s)";
			$this->query($sql,array($data['userId'],$time,$credit));
		}
	}
	
	/**
	 *
	 * @param array $data 用户的数据 id和credit：积分
	 * @param int $day 0为今天，1为昨天，2为前天，依次向之前的日期推算
	 * @return Ambigous <number, NULL, \DateTime>
	 */
	public function isSign($data,$day=0){
		$isHas = 0;
		$date = date('Y-m-d');
		$starTime = strtotime($date)-86400*$day;
		$endTime = strtotime($date.' 23:59:59')-86400*$day;
		$sql="select count(sid) as count from hb_bussiness_sign_info where uid = ".$data['userId']." and sign_time>=$starTime and sign_time<= $endTime ";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$isHas = $result->getData('count')?$result->getData('count'):0;
		}
		if($isHas){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * 得到一周的签到情况
	 * @param unknown $userId
	 * @return Ambigous <multitype:, NULL, \DateTime>
	 */
	public function getWeekSign($userId){
		$data = array();
		$i = 0;
		$day = date("w")?date("w"):7;
		$today = date('Y-m-d');		
		$statime = strtotime($today)-86400*($day-1);
		$endtime = strtotime($today)+86400*(8-$day);
		$sql="select this_credit,sign_time from hb_bussiness_sign_info where uid = %s and sign_time>='%s' and sign_time<'%s' ";
		$result = $this->query($sql,array($userId,$statime,$endtime));
		while($result->fetch_assoc()){
			$data[$i]['credit'] = $result->getData('this_credit');
			$data[$i]['signTime'] = $result->getData('sign_time');
			$i++;
		}
		return $data;
	}
	
	/**
	 * 发送次数加1
	 */
	public function setSendCount($mobile, $ip){
		$cache = new \haibao\user\cache\User();
		$cache->setSmsSendCount($mobile, $ip);
	}
	
	/**
	 * 得到用户填写资料的百分比
	 * @param unknown $userId
	 * @return number
	 */
	public function getUserDatumScale($userId){
		$data = 0;
		$this->setConfig('haibao_dz3');
		$sql="select profileprogress from hb_common_member_status where uid = $userId";	
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$data = $result->getData('profileprogress');
		}	
		
		return $data;
	}
	
	/**
	 * 得到积分数
	 */
	public function getUserCredits($userId){
		$credit = 0;
		$sql="select extcredits2 from hb_common_member_count where uid = $userId ";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$credit = $result->getData('extcredits2');
		}
		return $credit; 
	}
	
	/**
	 * 得到最新站内信个数
	 * @param unknown $uid
	 */
	public function getUserPmNum($userId){
		$sum = 0;
		$sql="select sum(isnew) as sum from hb_ucenter_pm_members where uid = $userId ";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$sum = $result->getData('sum');
		}
		return $sum;
	}
	
	/**
	 * 用户评论数
	 * @param unknown $userId
	 * @return string
	 */
	public function getUserCommentsNum($userId){
		$count = 0;
		$sql="select count(id) as count from z_hc_article_comments where user_id = $userId and is_public=999";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$count = $result->getData('count');
		}
		return $count;
	}
	
	/**
	 * 用户相册图片数
	 * @param unknown $userId
	 * @return string
	 */
	public function getUserAlbumNum($userId){
		$count = 0;
		$sql="select count(picid) as count from hb_home_pic where uid = $userId and  status = 0";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$count = $result->getData('count');
		}
		return $count;
	}
	
	/**
	 * 得到用户分级
	 * @param unknown $userId
	 * @return multitype:NULL Ambigous <NULL, \DateTime>
	 */
	public function getUserGroup($userId){
		$data = array();
		$sql="SELECT ug.groupid,ug.grouptitle,ug.stars FROM hb_common_member cm LEFT JOIN hb_common_usergroup ug ON cm.groupid = ug.groupid WHERE uid = ".$userId." LIMIT 1";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$data['groupid'] = $result->getData('groupid');
			$data['grouptitle'] = $result->getData('grouptitle');
			$data['stars'] = $result->getData('stars');
		}
		return $data;
	}
	/**
	 * 用户imarker收藏
	 * @param unknown $userId
	 * @return Ambigous <multitype:, NULL, \DateTime>
	 */
	public function getUserImarker($userId){
		$data = array();
		$sql="select count(favid) as count from hb_home_favorite where uid = $userId and isread = 0 ";	
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$data = $result->getData('count');
		}
		return $data;
	}
	
	/**
	 * pk台喜欢
	 * @param unknown $userId
	 * @return string
	 */
	public function addPkLike($userId,$threadId,$pkId){
		$today = date('Y-m-d');
		$tomorrow = date('Y-m-d',strtotime("+1 days"));
		$voteCount = 0;
		$sql="select count(id) as count from hb_zj_pk_vote_history_byx where pk_id=".$pkId." and uid=".$userId." and datetime >= '".$today."' and datetime< '".$tomorrow."' ";
		$historyByx = $this->query($sql);
		while($historyByx->fetch_assoc()){
			if($historyByx->getData('count')){
				return false;
			}
		}
		$sql="select votecount from hb_zj_pk_vote_byx where pk_id=".$pkId." and `thread_id`=".$threadId."";
		$voteResult = $this->query($sql);
		while($voteResult->getData('votecount')){
			$voteCount = $voteResult->getData('votecount');
		}
		$voteCount = intval($voteCount)+1;
		$sql="replace into hb_zj_pk_vote_byx (`pk_id`,`thread_id`,`votecount`) values('{$pkId}','{$threadId}','{$voteCount}')";
		$this->query($sql);
		$sql="insert into hb_zj_pk_vote_history_byx (`pk_id`,`thread_id`,`uid`,`datetime`) values('{$pkId}','{$threadId}','{$userId}','".date('Y-m-d H:i:s')."')";
		$this->query($sql);
		return true;
	}
	
	public function getPkLike($pkId){
		$data = array();
		$sql="select pk_id,thread_id,votecount from hb_zj_pk_vote_byx where pk_id = $pkId ";
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$data[$result->getData('thread_id')] = $result->getData('votecount');
		}
		return $data;
	}
	
	public function addSystemMessage($arrData){
		$array = array_values($arrData);
		$sql = "insert into hb_home_notification (uid,type,new,note,dateline,from_idtype,category) value (%s,%s,%s,%s,%s,%s,%s)";
		$this->query($sql,$array);
		//update
		$uid = $arrData['uid'];
		$sql = "update hb_common_member set newprompt=newprompt+1 where uid=%s";
		$this->query($sql,array($uid));
	}
	
	public function checkNicknameWithoutSelf($uid,$nickname){
		$sql = "select id from `auth_user` where nickname=%s and id != %s limit 1";
		$result = $this->query($sql, array(
				$nickname,$uid
		));
		return $result->fetch_assoc();
	}
	
	private function getSessionId($userId){
		$str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		$n=8;
		$len = strlen($str)-1;
		
		$s = '';
		for($i=0;$i<$n;$i++) {
			$s .= $str[mt_rand(0,$len)];
		}
		$timesap = time();
		$s = $s . $userId . $timesap . rand(1000, 10000);
		return md5($s);
	}
	
	/**
	 * 同步用户信息到sns_profile表中
	 * 之前老的数据可能没有设置过邮箱，这里做了更新操作
	 * 
	 * @param \haibao\user\model\data\authuser $model
	 * @param \haibao\user\model\data\authuser $profileModel
	 */
	private function saveSnsProfile($model){
		$data = new \haibao\user\data\snsmyprofile();
		$profile = $data->getProfileByUserId($model->Id);
		
		if($profile){
			$sql = 'update snsmyprofile set last_online=%s,is_email_verified=%s where user_id=%s';
			$this->query($sql, array(
				date('Y-m-d H:i:s'), \haibao\user\model\data\SnsMyProfile::EMAIL_VERIFIED_YES, $model->Id
			));
		}else{
			$profileModel = new \haibao\user\model\data\SnsMyProfile();
			$profileModel->user_id = $model->Id;
			$profileModel->username = $model->username;
			$profileModel->is_staff = $model->is_staff;
			$profileModel->last_online = new \DateTime();
			$profileModel->is_email_verified = \haibao\user\model\data\SnsMyProfile::EMAIL_VERIFIED_YES;
			$data = new \haibao\user\data\snsmyprofile();
			$data->addSnsProfile($profileModel);
		}
	}
	
	/**
	 * 添加ucenter注册用户初始信息
	 * 
	 * @param \haibao\user\model\data\authuser $model
	 */
	private function addUcenterData($model){
		$user_id = $model->Id;
		$name = $model->username;
		$password = $model->password;
		$email = $model->email ? $model->email : '';
		
		$emailstatus = 1;
		$avatarstatus= 0;
		$timenow = time();
		
		$sql = 'replace into hb_ucenter_members(uid,username,`password`,email,regdate) values(%s,%s,%s,%s,%s)';
		$this->logResult($sql);
		$this->query($sql, array(
			$user_id, $name, $password, $email, $timenow
		));
		
		$sql = 'replace into hb_common_member(uid,email,username,`password`,groupid,emailstatus,avatarstatus,regdate,credits) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)';
		$this->logResult($sql);
		$this->query($sql, array(
			$user_id, $email, $name, $password, '11', $emailstatus, $avatarstatus, $timenow, '0',
		));
		
		$sql = 'replace into hb_common_member_count(uid,extcredits1,extcredits2) values(%s,%s,%s)';
		$this->logResult($sql);
		$this->query($sql, array(
			$user_id, '0', '0',
		));
		
		$sql = 'replace into hb_common_member_status(uid) values(%s)';
		$this->logResult($sql);
		$this->query($sql, array(
				$user_id
		));
		
		$sql ='replace into hb_common_member_profile(uid) values(%s)';
		$this->logResult($sql);
		$this->query($sql, array($user_id));
		
		$blockpostion=addslashes('a:3:{s:5:"block";a:1:{s:12:"frame`frame1";a:3:{s:4:"attr";a:4:{s:4:"name";s:6:"frame1";s:8:"moveable";s:5:"false";s:9:"className";s:8:"frame cl";s:6:"titles";s:0:"";}s:18:"column`frame1_left";a:3:{s:4:"attr";a:2:{s:4:"name";s:11:"frame1_left";s:9:"className";s:8:"z column";}s:13:"block`profile";a:1:{s:4:"attr";a:3:{s:4:"name";s:7:"profile";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:6:"头像";s:4:"href";s:63:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=profile";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:13:"block`visitor";a:1:{s:4:"attr";a:3:{s:4:"name";s:7:"visitor";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"最近访客";s:4:"href";s:75:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=friend&view=visitor";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}}s:20:"column`frame1_center";a:10:{s:4:"attr";a:2:{s:4:"name";s:13:"frame1_center";s:9:"className";s:8:"z column";}s:11:"block`album";a:1:{s:4:"attr";a:3:{s:4:"name";s:5:"album";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:6:"相册";s:4:"href";s:80:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=album&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`block3";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"block3";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"迷你博客";s:4:"href";s:0:"";s:5:"color";s:0:"";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:10:"block`feed";a:1:{s:4:"attr";a:3:{s:4:"name";s:4:"feed";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"小道消息";s:4:"href";s:79:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=home&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:10:"block`blog";a:1:{s:4:"attr";a:3:{s:4:"name";s:4:"blog";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:6:"日志";s:4:"href";s:79:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=blog&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`block1";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"block1";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:18:"我喜欢的明星";s:4:"href";s:0:"";s:5:"color";s:0:"";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`block2";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"block2";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:18:"我喜欢的品牌";s:4:"href";s:0:"";s:5:"color";s:0:"";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`thread";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"thread";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"最新帖子";s:4:"href";s:81:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=thread&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`friend";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"friend";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:15:"我的好盆友";s:4:"href";s:81:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=friend&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:10:"block`wall";a:1:{s:4:"attr";a:3:{s:4:"name";s:4:"wall";s:9:"className";s:15:"block move-span";s:6:"titles";a:4:{i:0;a:8:{s:4:"text";s:9:"留言板";s:4:"href";s:60:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=wall";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}i:1;a:8:{s:4:"text";s:6:"全部";s:4:"href";s:60:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=wall";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:5:"y xw0";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}}}}s:13:"currentlayout";s:3:"1:3";s:10:"parameters";a:9:{s:6:"friend";a:2:{s:5:"title";s:15:"我的好盆友";s:7:"shownum";i:10;}s:5:"music";a:3:{s:7:"mp3list";a:2:{i:0;a:3:{s:6:"mp3url";s:43:"http://stream15.qqmusic.qq.com/35036372.mp3";s:7:"mp3name";s:15:"爸爸去哪儿";s:4:"cdbj";s:0:"";}i:1;a:3:{s:6:"mp3url";s:43:"http://stream13.qqmusic.qq.com/30815558.mp3";s:7:"mp3name";s:13:"I Remember Me";s:4:"cdbj";s:0:"";}}s:6:"config";a:8:{s:7:"showmod";s:7:"default";s:7:"autorun";s:4:"true";s:7:"shuffle";s:4:"true";s:12:"crontabcolor";s:7:"#D2FF8C";s:11:"buttoncolor";s:7:"#1F43FF";s:9:"fontcolor";s:7:"#1F43FF";s:9:"crontabbj";s:0:"";s:6:"height";i:100;}s:5:"title";s:9:"音乐盒";}s:6:"block1";a:2:{s:5:"title";s:18:"我喜欢的明星";s:7:"content";s:0:"";}s:6:"block2";a:2:{s:5:"title";s:18:"我喜欢的品牌";s:7:"content";s:0:"";}s:4:"feed";a:2:{s:5:"title";s:12:"小道消息";s:7:"shownum";i:10;}s:6:"block3";a:2:{s:5:"title";s:12:"迷你博客";s:7:"content";s:0:"";}s:6:"block4";a:2:{s:5:"title";s:18:"迷你博客广播";s:7:"content";s:0:"";}s:6:"block5";a:2:{s:5:"title";s:12:"最新帖子";s:7:"content";s:0:"";}s:4:"blog";a:3:{s:5:"title";s:6:"日志";s:7:"shownum";i:6;s:11:"showmessage";i:150;}}}');
		$sql = 'replace into hb_common_member_field_home(uid,blockposition) values(%s,%s)';
		$this->logResult($sql);
		$this->query($sql, array(
			$user_id, $blockpostion
		));
		
		$sql = 'replace into hb_common_member_field_forum(uid,customshow,groupterms) values(%s,%s,%s)';
		$this->logResult($sql);
		$this->query($sql, array(
			$user_id, '26', 'a:0:{}'
		));
	}
	
	/**
	 * 生成6位随机数字
	 */
	private function generateCode($length = 6){
		return rand(pow(10,($length-1)), pow(10,$length)-1);
	}
	
	/**
	 * 添加绑定的第三方用户ID
	 */
	private function addBind($type, $userId, $thirdId){
		$model = new \haibao\user\model\data\SnsWeiboBind();
		$model->user_id = $userId;
		if($type == \haibao\user\model\data\SnsWeiboBind::LOGIN_QQ){
			$model->qquid = $thirdId;
		}elseif($type == \haibao\user\model\data\SnsWeiboBind::LOGIN_WB){
			$model->wbuid = $thirdId;
		}elseif($type == \haibao\user\model\data\SnsWeiboBind::LOGIN_WX){
			$model->wxuid = $thirdId;
		}
		
		$data = new \haibao\user\data\SnsWeiboBind();
		$data->addBind($model);
	}
	
	/**
	 * 获取用户消息数量
	 */
	private function getMessageCount($userId){
		//$sql = "select `newpm` from hb_common_member where uid=%s";
		$sql = "select count(*) as `newpm` from hb_home_notification where uid=%s and new=1";
		$result = $this->query($sql, array($userId));
		$aResult = $result->fetch_assoc();
		return $aResult['newpm'];
	}
	
	/**
	 * 记录日志到/tmp/下
	 */
	private function logResult($data){
	    if(PHP_OS == 'Linux'){
    		$fp = fopen('/tmp/user.txt', "a");	
    		flock($fp, LOCK_EX) ;
    		$line = "[" . date("Y-m-d H:i:s") . "]\t";
    		$line .= print_r($data, true);
    		$line .= "\n";
    		fwrite($fp, $line);
    		flock($fp, LOCK_UN); 
    		fclose($fp);
	    }
	}
}